package com.spaceobj.chess.controller;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spaceobj.chess.common.Result;
import com.spaceobj.chess.entity.Game;
import com.spaceobj.chess.service.GameService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;

@Tag(name = "游戏管理", description = "游戏相关接口")
@RestController
@RequestMapping("/api/games")
@RequiredArgsConstructor
public class GameController {

    private final GameService gameService;

    @Operation(summary = "创建游戏")
    @PostMapping
    public Result<Game> createGame(@RequestBody Game game) {
        gameService.save(game);
        return Result.success(game);
    }

    @Operation(summary = "更新游戏")
    @PutMapping("/{id}")
    public Result<Game> updateGame(
            @Parameter(description = "游戏ID") @PathVariable Integer id,
            @RequestBody Game game) {
        game.setGameId(id);
        gameService.updateById(game);
        return Result.success(game);
    }

    @Operation(summary = "删除游戏")
    @DeleteMapping("/{id}")
    public Result<Void> deleteGame(@Parameter(description = "游戏ID") @PathVariable Integer id) {
        gameService.removeById(id);
        return Result.success();
    }

    @Operation(summary = "获取游戏详情")
    @GetMapping("/{id}")
    public Result<Game> getGame(@Parameter(description = "游戏ID") @PathVariable Integer id) {
        return Result.success(gameService.getById(id));
    }

    @Operation(summary = "分页查询游戏")
    @GetMapping
    public Result<Page<Game>> listGames(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "游戏状态") @RequestParam(required = false) Integer status) {
        Page<Game> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Game> queryWrapper = new LambdaQueryWrapper<>();
        if (status != null) {
            queryWrapper.eq(Game::getResult, status);
        }
        return Result.success(gameService.page(pageParam, queryWrapper));
    }
} 